<?php

class SiteController extends AdminController {

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id = 1) {
        $model = $this->loadModel($id);
        
        $old_filename = $model->configuration_favicon;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['site_configuration'])) {
            $model->attributes = $_POST['site_configuration'];
            
            //file upload
            $file = CUploadedFile::getInstance($model, 'configuration_favicon');
            $filename = '';
            if ((is_object($file) && get_class($file) === 'CUploadedFile')) {
                $filename = function_lib::url_title($file->name);
                $model->configuration_favicon = CUploadedFile::getInstance($model, 'configuration_favicon');
                $model->configuration_favicon = $filename;
            }
            
            if ($model->save())
                //file upload
                if (is_object($file)) {
                    $model->configuration_favicon = CUploadedFile::getInstance($model, 'configuration_favicon');
                    if($model->configuration_favicon->saveAs(Yii::app()->params['config']['updir']['favicon'] . $filename)) {
                        if(file_exists(Yii::app()->params['config']['updir']['favicon'].$old_filename)) {
                            unlink(Yii::app()->params['config']['updir']['favicon'].$old_filename);
                        }
                    }
                }
                
                $this->redirect(array('update'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = site_configuration::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'site-support-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
